package com.welkom.everydate.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.welkom.everydate.domain.User;
@Repository
public class UserDao extends BaseDao {
	public static final String GET_USER_BY_NAME="getUserByUserName"; 
	public static final String GET_USER_BY_ID="getUserById";
	public static final String QUERY_USER_BY_PAGE="queryUserByPage";
	public static final String GET_TOTAL_COUNT_BY_CONDITION="getTotalCountByCondition";
	public static final String UPDATE_USER="updateUser";
	public static final String ADD_USER="insertUser";
	public static final String DELETE_USER_BY_ID="deleteUserById";
	public static final String GET_ALL_USERS="getAlllUsers";
	@Resource 
	private RoleDao roleDao;
	public User getUserByUserName(String userName){
		Map<String,Object> parameters=new HashMap<String,Object>();
		parameters.put("user_name", userName);
		User user= (User)getSqlMapClientTemplate().queryForObject(GET_USER_BY_NAME,parameters);
		user.setRoles(roleDao.getRolesByUserId(user.getUserId()));
		return user;
	}
	
	public User getUserById(long userId){
		Map<String,Object> parameters=new HashMap<String,Object>();
		parameters.put("user_id", userId);
		return (User)getSqlMapClientTemplate().queryForObject(GET_USER_BY_ID, parameters);
	}
	
	public List<User> queryUserByPage(User user,int startIndex,int pageSize){
		Map<String,Object> parameters=new HashMap<String,Object>();
		parameters.put("user_name", user.getUserName());
		parameters.put("user_enabled", user.getUserEnabled());
		parameters.put("startIndex", startIndex);
		parameters.put("pageSize", pageSize);
		return (List<User>) getSqlMapClientTemplate().queryForList(QUERY_USER_BY_PAGE, parameters);
	}
	
	public List<User> getAllUsers(){
		return (List<User>) getSqlMapClientTemplate().queryForList(GET_ALL_USERS);
	}
	
	public int getTotalCountByCondition(User user){
		return (Integer)getSqlMapClientTemplate().queryForObject(GET_TOTAL_COUNT_BY_CONDITION,user);
	}
	
	public void updateUser(User user){
		getSqlMapClientTemplate().update(UPDATE_USER, user);
	}
	
	public void addUser(User user){
		getSqlMapClientTemplate().insert(ADD_USER,user);
	}
	
	public void removeUserById(long userId){
		Map<String,Object> parameters=new HashMap<String,Object>();
		parameters.put("user_id", userId);
		getSqlMapClientTemplate().delete(DELETE_USER_BY_ID, parameters);
	}
}
